<?php 
function __autoload($class_name) {
    if (class_exists($class_name, false) || interface_exists($class_name, false)) {
        return;
    }
    $file = str_replace('_', DIRECTORY_SEPARATOR, $class_name) . '.php';
    if (preg_match('/[^a-z0-9\\/\\\\_.-]/i', $file)) {
        return;
    }
    include_once $file;
}

/**
 * 字符过滤
 *
 * @param String $string
 * @return String
 */
function saddslashes($string) {
    if(is_array($string)) {
        foreach($string as $key => $val) {
            $string[$key] = saddslashes($val);
        }
    } else {
        $string = addslashes($string);
    }
    return $string;
}

function sstripslashes($string) {
    if(is_array($string)) {
        foreach($string as $key => $val) {
            $string[$key] = sstripslashes($val);
        }
    } else {
        $string = stripslashes($string);
    }
    return $string;
}

/**
 * 格式化输出
 * @param mix $var
 */
function f($var) {
    echo "<pre>";
    print_r($var);
    echo "</pre>";
}

/**
 * 调试
 * @param mix $var
 */
if(!function_exists('d'))
{
    function d($var) {
        echo "<pre>";
        print_r($var);
        echo "</pre>";
        exit;
    }
}


/**
 * 安全过滤
 *
 * @param string $str
 * @param bool $html_filter
 * @return string
 */
function my_str_replace( $str, $html_filter=true )
{
    if(!$str) return ;
    $str = trim( $str );
    $str = addslashes( $str );
    if ( $html_filter ) $str = htmlspecialchars( $str );
    $str = preg_replace( '/[\x00-\x08\x0b\x0c\x0e-\x1f]/', '', $str );
    return $str;
}

/**
 * 随即密码
 *
 * @param int $len
 * @param string $format
 * @return string
 */
function string_mkPasswd($len=6,$format='ALL') {
    switch(strtolower($format)) {
        case 'all':
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
            break;
        case 'char':
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
            break;
        case 'char2':
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~';
            break;
        case 'num':
            $chars = '0123456789';
            break;
        default :
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
            break;
    }

    mt_srand((double)microtime()*1000000*getmypid());
    $passwd = '';
    while (strlen($passwd)<$len) $passwd .= substr($chars,(mt_rand()%strlen($chars)),1);
    return $passwd;
}

function cutstr($string, $length, $dot = ' ...') {

    if (! defined ( 'CHARSET' )) {
        define ( 'CHARSET', 'utf-8' );
    }

    if (strlen ( $string ) <= $length) {
        return $string;
    }

    $string = str_replace ( array ('&amp;', '&quot;', '&lt;', '&gt;' ), array ('&', '"', '<', '>' ), $string );

    $strcut = '';
    if (strtolower ( CHARSET ) == 'utf-8') {

        $n = $tn = $noc = 0;
        while ( $n < strlen ( $string ) ) {

            $t = ord ( $string [$n] );
            if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1;
                $n ++;
                $noc ++;
            } elseif (194 <= $t && $t <= 223) {
                $tn = 2;
                $n += 2;
                $noc += 2;
            } elseif (224 <= $t && $t < 239) {
                $tn = 3;
                $n += 3;
                $noc += 2;
            } elseif (240 <= $t && $t <= 247) {
                $tn = 4;
                $n += 4;
                $noc += 2;
            } elseif (248 <= $t && $t <= 251) {
                $tn = 5;
                $n += 5;
                $noc += 2;
            } elseif ($t == 252 || $t == 253) {
                $tn = 6;
                $n += 6;
                $noc += 2;
            } else {
                $n ++;
            }

            if ($noc >= $length) {
                break;
            }

        }
        if ($noc > $length) {
            $n -= $tn;
        }

        $strcut = substr ( $string, 0, $n );

    } else {
        for($i = 0; $i < $length; $i ++) {
            $strcut .= ord ( $string [$i] ) > 127 ? $string [$i] . $string [++ $i] : $string [$i];
        }
    }

    $strcut = str_replace ( array ('&', '"', '<', '>' ), array ('&amp;', '&quot;', '&lt;', '&gt;' ), $strcut );

    return $strcut . $dot;
}

//获取IP
function getIP() {
    $cip = getenv ( 'HTTP_CLIENT_IP' );
    $xip = getenv ( 'HTTP_X_FORWARDED_FOR' );
    $rip = getenv ( 'REMOTE_ADDR' );
    $srip = $_SERVER ['REMOTE_ADDR'];
    if ($cip && strcasecmp ( $cip, 'unknown' )) {
        $onlineip = $cip;
    } elseif ($xip && strcasecmp ( $xip, 'unknown' )) {
        $onlineip = $xip;
    } elseif ($rip && strcasecmp ( $rip, 'unknown' )) {
        $onlineip = $rip;
    } elseif ($srip && strcasecmp ( $srip, 'unknown' )) {
        $onlineip = $srip;
    }

    preg_match ( "/[\d\.]{7,15}/", $onlineip, $match );
    return $match [0] ? $match [0] : 'unknown';
}

/**
 * 查IP所在地(需纯真IP数据包)
 * 来自discuz
 */
function ip2addr($ip) {
    //IP数据文件路径
    $dat_path = dirname(__FILE__) . '/wry.dat';

    //检查IP地址
    if (! preg_match ( "/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $ip )) {
        return 'IP Address Error';
    }
    //打开IP数据文件
    if (! $fd = @fopen ( $dat_path, 'rb' )) {
        return 'IP date file not exists or access denied';
    }

    //分解IP进行运算，得出整形数
    $ip = explode ( '.', $ip );
    $ipNum = $ip [0] * 16777216 + $ip [1] * 65536 + $ip [2] * 256 + $ip [3];

    //获取IP数据索引开始和结束位置
    $DataBegin = fread ( $fd, 4 );
    $DataEnd = fread ( $fd, 4 );
    $ipbegin = implode ( '', unpack ( 'L', $DataBegin ) );
    if ($ipbegin < 0)
        $ipbegin += pow ( 2, 32 );
    $ipend = implode ( '', unpack ( 'L', $DataEnd ) );
    if ($ipend < 0)
        $ipend += pow ( 2, 32 );
    $ipAllNum = ($ipend - $ipbegin) / 7 + 1;

    $BeginNum = 0;
    $EndNum = $ipAllNum;

    $ip1num = 0;
    $ip2num = 0;
    $ipAddr1='';
    $ipAddr2='';
    //使用二分查找法从索引记录中搜索匹配的IP记录
    while ( $ip1num > $ipNum || $ip2num < $ipNum ) {
        $Middle = intval ( ($EndNum + $BeginNum) / 2 );

        //偏移指针到索引位置读取4个字节
        fseek ( $fd, $ipbegin + 7 * $Middle );
        $ipData1 = fread ( $fd, 4 );
        if (strlen ( $ipData1 ) < 4) {
            fclose ( $fd );
            return 'System Error';
        }
        //提取出来的数据转换成长整形，如果数据是负数则加上2的32次幂
        $ip1num = implode ( '', unpack ( 'L', $ipData1 ) );
        if ($ip1num < 0)
            $ip1num += pow ( 2, 32 );

        //提取的长整型数大于我们IP地址则修改结束位置进行下一次循环
        if ($ip1num > $ipNum) {
            $EndNum = $Middle;
            continue;
        }

        //取完上一个索引后取下一个索引
        $DataSeek = fread ( $fd, 3 );
        if (strlen ( $DataSeek ) < 3) {
            fclose ( $fd );
            return 'System Error';
        }
        $DataSeek = implode ( '', unpack ( 'L', $DataSeek . chr ( 0 ) ) );
        fseek ( $fd, $DataSeek );
        $ipData2 = fread ( $fd, 4 );
        if (strlen ( $ipData2 ) < 4) {
            fclose ( $fd );
            return 'System Error';
        }
        $ip2num = implode ( '', unpack ( 'L', $ipData2 ) );
        if ($ip2num < 0)
            $ip2num += pow ( 2, 32 );

        //没找到提示未知
        if ($ip2num < $ipNum) {
            if ($Middle == $BeginNum) {
                fclose ( $fd );
                return 'Unknown';
            }
            $BeginNum = $Middle;
        }
    }

    $ipFlag = fread ( $fd, 1 );
    if ($ipFlag == chr ( 1 )) {
        $ipSeek = fread ( $fd, 3 );
        if (strlen ( $ipSeek ) < 3) {
            fclose ( $fd );
            return 'System Error';
        }
        $ipSeek = implode ( '', unpack ( 'L', $ipSeek . chr ( 0 ) ) );
        fseek ( $fd, $ipSeek );
        $ipFlag = fread ( $fd, 1 );
    }

    if ($ipFlag == chr ( 2 )) {
        $AddrSeek = fread ( $fd, 3 );
        if (strlen ( $AddrSeek ) < 3) {
            fclose ( $fd );
            return 'System Error';
        }
        $ipFlag = fread ( $fd, 1 );
        if ($ipFlag == chr ( 2 )) {
            $AddrSeek2 = fread ( $fd, 3 );
            if (strlen ( $AddrSeek2 ) < 3) {
                fclose ( $fd );
                return 'System Error';
            }
            $AddrSeek2 = implode ( '', unpack ( 'L', $AddrSeek2 . chr ( 0 ) ) );
            fseek ( $fd, $AddrSeek2 );
        } else {
            fseek ( $fd, - 1, SEEK_CUR );
        }

        while ( ($char = fread ( $fd, 1 )) != chr ( 0 ) )
            $ipAddr2 .= $char;

        $AddrSeek = implode ( '', unpack ( 'L', $AddrSeek . chr ( 0 ) ) );
        fseek ( $fd, $AddrSeek );

        while ( ($char = fread ( $fd, 1 )) != chr ( 0 ) )
            $ipAddr1 .= $char;
    } else {
        fseek ( $fd, - 1, SEEK_CUR );
        while ( ($char = fread ( $fd, 1 )) != chr ( 0 ) )
            $ipAddr1 .= $char;

        $ipFlag = fread ( $fd, 1 );
        if ($ipFlag == chr ( 2 )) {
            $AddrSeek2 = fread ( $fd, 3 );
            if (strlen ( $AddrSeek2 ) < 3) {
                fclose ( $fd );
                return 'System Error';
            }
            $AddrSeek2 = implode ( '', unpack ( 'L', $AddrSeek2 . chr ( 0 ) ) );
            fseek ( $fd, $AddrSeek2 );
        } else {
            fseek ( $fd, - 1, SEEK_CUR );
        }
        while ( ($char = fread ( $fd, 1 )) != chr ( 0 ) ) {
            $ipAddr2 .= $char;
        }
    }
    fclose ( $fd );

    //最后做相应的替换操作后返回结果
    if (preg_match ( '/http/i', $ipAddr2 )) {
        $ipAddr2 = '';
    }
    $ipaddr = "$ipAddr1 $ipAddr2";
    $ipaddr = preg_replace ( '/CZ88.Net/is', '', $ipaddr );
    $ipaddr = preg_replace ( '/^s*/is', '', $ipaddr );
    $ipaddr = preg_replace ( '/s*$/is', '', $ipaddr );
    if (preg_match ( '/http/i', $ipaddr ) || $ipaddr == '') {
        $ipaddr = 'Unknown';
    }

    //转成utf8
    return mb_convert_encoding ( $ipaddr, "utf-8", "gbk" );
}
/**
 * 分页函数
 * @param int(当前页面) $curPage
 * @param int(每页多少信息) $perPage
 * @param string $sql
 * @return array
 */
function findPage($curPage, $perPage, $sql, $url) {
    //统计信息个数
    //$allNumber = Ext_Mysql::getInstance()->fetchNums($sql);
    $rs = Ext_Mysql::getInstance()->fetchRow($sql);
    $allNumber = count($rs);
    //总页面数量
    $totalPage = ceil($allNumber/$perPage);
    $totalPage = $totalPage ? ($totalPage) : (1);
    //修改当前页面
    if ($curPage < 1) {
        $curPage = 1;
    } else if ($curPage > $totalPage) {
        $curPage = $totalPage;
    }
    return array(
        "curpage" => $curPage,
        "totalpage" => $totalPage,
        "data" => Ext_Mysql::getInstance()->fetchRow($sql . " LIMIT " . ($curPage - 1) * $perPage . ", " . $perPage),
        "totalnumber" => $allNumber,
        "url" => (strpos($url, "?") === false) ? ($url . "?page=") : (rtrim($url, "&") . "&page="),
    );
}

/**
 * safe_file_get_contents() 用共享锁模式打开文件并读取内容，可以避免在并发写入造成的读取不完整问题
 *
 * @param string $filename
 *
 */
function safe_file_get_contents($filename) {

    if (! is_readable ( $filename )) {
        return false;
    }

    $filesize = filesize ( $filename );
    if ($filesize <= 0) {
        return false;
    }

    $fp = @fopen ( $filename, "rb" );
    if ($fp) {
        flock ( $fp, LOCK_EX );
        $contents = @fread ( $fp, $filesize );
        flock ( $fp, LOCK_UN );
        fclose ( $fp );
        return $contents;
    } else {
        return false;
    }
}

/**
 * safe_file_put_contents() 一次性完成打开文件，写入内容，关闭文件三项工作，并且确保写入时不会造成并发冲突
 *
 * @param string $filename
 * @param string $contents
 *
 * @return boolean
 */
function safe_file_put_contents($filename, $contents) {

    $fp = @fopen ( $filename, "wb" );
    if ($fp) {
        flock ( $fp, LOCK_EX );
        @fwrite ( $fp, $contents );
        flock ( $fp, LOCK_UN );
        fclose ( $fp );
        return true;
    } else {
        return false;
    }
}

/**
 * cache_read() 读取缓存 以return array();形式读取
 *
 * @param string $file
 * @param string $mode
 *
 * @return $data
 */
function cache_read($file, $mode = 1) {
    if (! file_exists ( $file ) || filesize ( $file ) <= 0) {
        return false;
    }
    return $mode ? include ($file) : safe_file_get_contents ( $file );
}

/**
 * cache_write() 写入缓存  以return array();形式写入
 *
 * @param string $file
 * @param string $array
 *
 * @return boolean
 */
function cache_write($file, $array) {
    if (is_array ( $array )) {
        $data = "<?php\n return " . var_export ( $array, true ) . "\n?>";
        safe_file_put_contents ( $file, $data );
        return true;
    } else {
        return false;
    }
}

/**
 * cache_delete() 删除缓存
 *
 * @param string $file
 *
 * @return boolean
 */
function cache_delete($file) {
    if (file_exists ( $file )) {
        @unlink ( $file );
        return true;
    } else {
        return false;
    }
}

/**
 * SQL入库
 *
 * @param Array $arr
 * @param String $table
 * @return String
 */
function makeInsertSqlFromArray($arr, $table) {
    $str1 = '';
    $str2 = '';
    foreach ( $arr as $k => $v ) {
        $str1 .= "`{$k}`,";
        $str2 .= "'{$v}',";
    }

    $str = "INSERT INTO `{$table}` (" . trim ( $str1, ', ' ) . ") VALUES (" . trim ( $str2, ', ' ) . ")";
    return $str;
}

/*
* 由数组构造出SQL语句，用于更新数据回数据库，即UPDATE
*/
function makeUpdateSqlFromArray($arr, $table, $key = 'id') {
    $str = '';
    if (! isset ( $arr [$key] )) {
        d ( debug_backtrace () );
        ErrorExit ( "数据修改操作有误" );
    }
    foreach ( $arr as $k => $v ) {
        if ($k != $key)
            $str .= "`{$k}`='{$v}',";
        else
            $where = " WHERE `{$key}`='{$v}' LIMIT 1";
    }

    $str = "UPDATE `{$table}` SET " . trim ( $str, ', ' ) . $where;

    //if (ODINXU_DEBUG) echo $str ."\r\n";
    return $str;
}
/*
* 由数组构造出SQL语句，用于条件查询，用来检查刚刚INSERT的数据。
*/
function makeSelectIdWhereSqlFromArray($arr, $table, $key = 'id') {
    $where = '';
    foreach ( $arr as $k => $v ) {
        if ($k != $key)
            $where .= "`{$k}`='{$v}' AND ";
    }

    $str = "SELECT `{$key}` FROM `{$table}` WHERE " . substr ( $where, 0, strlen ( $where ) - 4 );
    return $str;
}

//返回当前天0时0分0秒的时间，如果$outstring为true则返回该时间的字符串形式，否则为时间戳
function GetTime_Today0($outstring = false) {
    $str_today0 = strftime ( "%Y-%m-%d", time () );
    $result = strtotime ( $str_today0 );
    if ($outstring)
        return strftime ( "%Y-%m-%d %H:%M:%S", $result );
    else
        return $result;
}

//将整数时间，转换成标准格式的字符串
function GetTimeString($srcTimeStamp) {
    return strftime ( "%Y-%m-%d %H:%M:%S", $srcTimeStamp );
}

/**
 * 解决serialize序列化浮点数问题
 *
 $val = 3.14159;
 var_dump($val);  // initial value: float(3.14159)
 $val = serialize($val);
 var_dump($val);  // standart float format: string(55) "d:3.14158999999999988261834005243144929409027099609375;"
 $val = preg_replace('/d:([0-9]+(\.[0-9]+)?([Ee][+-]?[0-9]+)?);/e', "'d:'.((float)$1).';'", $val);
 var_dump($val);  // compact float format: string(10) "d:3.14159;"
 $val = unserialize($val);
 var_dump($val);  // unserialization successed: float(3.14159)
 * @param  $var
 */
function iSerialize($var) {
    $var = serialize ( $var );
    return preg_replace ( '/d:([0-9]+(\.[0-9]+)?([Ee][+-]?[0-9]+)?);/e', "'d:'.(round($1,2)).';'", $var );
}

function cutString($str, $len, $char = '…', $encode = '') {

    ! $encode && $encode = 'utf-8';
    if (strlen ( $str ) < $len)
        return $str;

    $s = '';
    $i2 = 0;
    for($i = 0; $i < mb_strlen ( $str, $encode ); $i ++) {
        $one = mb_substr ( $str, $i, 1, $encode );

        if (strlen ( $one ) == 2) {
            $i2 ++;
        }
        if ($i2 >= $len)
            break;
        $s .= $one;
        $i2 ++;
    }
    return $s . $char;
}

/**
 * 加载缓存文件
 */
function loadBaseCache($cachename) {
    global $_DCACHE;
    if ((!isset($_DCACHE[$cachename]) || (!is_array($_DCACHE[$cachename])))) {
        $fn_cache = CACHE_DIR . 'base/base_'. $cachename . '.php';          
        require_once($fn_cache); //载入缓存文件
    }
}

/*
 * 将数组，组合合并为字符串格式
 */
function combineData($arr, $level = 1, $key = null)
{
    if ($level == 1)
    {
        $str = '';
        foreach($arr as $k=>$v)
            $str .= "{$k}:{$v},";
        $str = trim($str, ',');
        return $str;
    }
    
    if ($level == 2)
    {
        if (empty($key))
            return false;
            
        $str = '';
        foreach($arr as $k=>$v) {
            if ($v <=0)     //去掉为0的
                continue;
            $str .= "{$key}:{$k}:{$v},";
        }
        $str = trim($str, ',');
        return $str;
    }   
}
/*
 * 将字符串数据拆分
 * 
 */
function extractData($str, $level = 1)
{
    $extr = ',';
    $extr2 = ':';
    if (empty($str))
        return null;
        
    $arr = explode($extr, $str);
    if (sizeof($arr)<=0)
        return null;
    
    $result = null;
    $count = count($arr);
    if ($level == 1)
    {
        //  "F:1000,W:800"  拆分成数组 F=1000; W=800;
        for($i=0;$i<$count;$i++)
        {
            $r = explode($extr2, $arr[$i]);
            $result[$r[0]] = $r[1];
        }
    }
    else if ($level == 2)
    {
        //  "B:2:1,T:3:3"  拆分成数组 
        for($i=0;$i<$count;$i++)
        {
            $r = explode($extr2, $arr[$i]);
            $result[$i]['k'] = $r[0];
            $result[$i]['v1'] = $r[1];
            $result[$i]['v2'] = $r[2];
        }
    }
    else if ($level == 3)
    {
        //  "B:2:1:4,T:3:3:5"  拆分成数组 
        for($i=0;$i<$count;$i++)
        {
            $r = explode($extr2, $arr[$i]);
            $result[$i]['k'] = $r[0];
            $result[$i]['v1'] = $r[1];
            $result[$i]['v2'] = $r[2];
            $result[$i]['v3'] = $r[3];
        }
    }
    return $result;
}

function MyEncode($array) {
    return addcslashes(json_encode($array), '\\');
}

/**
 * 文件下载
 * @param $filePath 文件路径
 * @return unknow_type
 */
function fileDown($filePath) 
{
    if ( ! is_file($filePath) ) 
    {
        return false;
    }
    $fp = fopen($filePath, 'rb');
    if ( ! $fp) 
    {
        return false;
    }
    Header('Content-Type:application/octet-stream;');
    Header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
    Header('Content-Length: ' . filesize($filePath));
    Header('Accept-Ranges: Bytes');
    Header("Cache-control: private");
    Header('Pragma: private');
    Header('Expires: 0');
    fpassthru($fp);
}

/**
 * 弹出框
 */
function alert($content = false, $url = "")
{
    $js = "<script>";
    $js .= $content ? ("alert('" . $content . "');") : ("");
    $js .= ($url == "") ? ("history.back();") : ("document.location.href='" . $url . "'");
    $js .= "</script>";
    echo $js;
    exit;
}

/**
 * 充值活动
 */
function pay_award($player_id,$pay_gold,$pay_time){
    $begTime = 1322006400;//11月23日 1322006400
    $endTime = 1322236800;//11月25日
    $pay_time = (int)$pay_time;
//  if($pay_time > $begTime && $pay_time < $endTime){
//      $dbConn = DbAgent::getInstance("mongo");
//      $today = strtotime(date("Y-m-d",time()));
//      $todayPay = $dbConn->fetchRow_mongodb(log_pay,array("player_id"=>$player_id,"pay_status"=>1,"insert_time"=>array('$gt'=>$today)),array("insert_time"),null);
//      //是否当天第一次充值
//      $firstPay = false;
//      if(count($todayPay) == 1)
//      {
//          $firstPay=true;
//      }
//      $title = "充值奖励";
//      $content = "感谢您的充值，你今天第1次充值获赠火种1枚，火种可配合火鸡食用，谢谢你的支持！";
//      if($firstPay)
//      {
//          //31211 火种
//          pay_award_mail($player_id,31211,1,$title,$content);
//      }

//      if($pay_gold >= 500 && $pay_gold <= 1999 )
//      {
//          pay_award_mail($player_id,28817,1,$title,"感谢您的充值，你获得单笔50元的充值奖励，可获赠感恩礼包*1，本奖励每次充值都可领取，谢谢你的支持！");
//          pay_award_mail($player_id,31213,1,$title,"感谢您的充值，你获得单笔50元的充值奖励，南瓜馅饼*1，本奖励每次充值都可领取，谢谢你的支持！");
//      }elseif($pay_gold >=2000 && $pay_gold <=4999)
//      {
//          pay_award_mail($player_id,28817,5,$title,"感谢您的充值，你获得单笔200元的充值奖励，可获赠感恩礼包*5，本奖励每次充值都可领取，谢谢你的支持！");
//          pay_award_mail($player_id,31213,4,$title,"感谢您的充值，你获得单笔200元的充值奖励，南瓜馅饼*4，本奖励每次充值都可领取，谢谢你的支持！");
//      }elseif($pay_gold >=5000 && $pay_gold <=9999)
//      {
//          pay_award_mail($player_id,28817,13,$title,"感谢您的充值，你获得单笔500元的充值奖励，可获赠感恩礼包*13，本奖励每次充值都可领取，谢谢你的支持！");
//          pay_award_mail($player_id,31213,10,$title,"感谢您的充值，你获得单笔500元的充值奖励，南瓜馅饼*10，本奖励每次充值都可领取，谢谢你的支持！");
//      }elseif($pay_gold >=10000 && $pay_gold <=19999)
//      {
//          pay_award_mail($player_id,28817,28,$title,"感谢您的充值，你获得单笔1000元的充值奖励，可获赠感恩礼包*28，本奖励每次充值都可领取，谢谢你的支持！");
//          pay_award_mail($player_id,31213,20,$title,"感谢您的充值，你获得单笔1000元的充值奖励，南瓜馅饼*20，本奖励每次充值都可领取，谢谢你的支持！");
//      }elseif($pay_gold >=20000 && $pay_gold <=49999)
//      {
//          pay_award_mail($player_id,28817,60,$title,"感谢您的充值，你获得单笔2000元的充值奖励，可获赠感恩礼包*60，本奖励每次充值都可领取，谢谢你的支持！");
//          pay_award_mail($player_id,31213,40,$title,"感谢您的充值，你获得单笔2000元的充值奖励，南瓜馅饼*40，本奖励每次充值都可领取，谢谢你的支持！");
//      }elseif($pay_gold >=50000)
//      {
//          pay_award_mail($player_id,28817,160,$title,"感谢您的充值，你获得单笔5000元的充值奖励，可获赠感恩礼包*160，本奖励每次充值都可领取，谢谢你的支持！");
//          pay_award_mail($player_id,31213,100,$title,"感谢您的充值，你获得单笔5000元的充值奖励，南瓜馅饼*100，本奖励每次充值都可领取，谢谢你的支持！");
//      }

//  }

    //peng+ 充值活动
    $mdb = Mdb::getInstance('mongo');
    $data = $mdb->getAll("charge_activity", array('st' => array('$lte'=>$pay_time), 'et' => array('$gte'=>$pay_time)), array(), array('gold'=>1)); //注意一定要按元宝排序一下
    $actItem = array();
    $goldsum = array();
    $pay_gold = (float)$pay_gold;
    //按100,200,300活动元宝说明
    foreach($data as $val)
    {
        if($val['type'] == 2)
        {//累积
            $key = $val['st'].$val['et'];
            //活动期间累计
            if(!isset($goldsum[$key]))
                $goldsum[$key] = $mdb->sum('log_pay', array("player_id"=>$player_id,"pay_status"=>1,"insert_time"=>array('$gte'=>$val['st'], '$lte'=>$val['et'])), 'pay_gold', 'player_id');
            if($goldsum[$key] >= $val['gold'])
            {
                //先记录最大的那条活动
                $actItem = $val;
            }else{
                //如果只充值了10元宝或充值了120元宝，当前循环到了活动元宝200
                break;
            }
        }else{//单笔
            if($pay_gold >= $val['gold'] && $pay_gold >= $actItem['gold'])
            {
                //获取最大的那个元宝记录
                $actItem = $val;
            }
        }
    }

    if($actItem)
    {
        if($actItem['type'] == 1)
        {
            //单笔
            pay_activity_award($actItem,$player_id);
        }else{
            //累积
            //扫描没有发过的，发过的不能再发了
            foreach($data as $val)
            {
                //getOne($collection, $wheres, $fields=array(), $orderby=array(), $returnId = false)
                if(!$mdb->getOne("charge_activity_log", array("role_id"=>$player_id, "ca_st"=>$val['st'], "ca_id"=>$val['id']), array("role_id"=>1)))
                {
                    pay_activity_award($val,$player_id);
                }
                if($val['id'] == $actItem['id'] && $val['st'] == $actItem['st'])
                    break;
            }
        }
    }
    //end
    
    //+zj 充值祈福
    $payPraySet = $mdb ->getRow(pay_pray_setting,array('begtime' => array('$lt'=>$pay_time), 'endtime' => array('$gt'=>$pay_time)),array('begtime'=>1));
    if(count($payPraySet)>0)
    {
        $playerPray = $mdb -> getRow(pay_pray,array('player_id'=>$player_id),array('mult'));
        if($playerPray['mult'] > 0)
        {
            $pray = round(($pay_gold * ($playerPray['mult'] -1)));
            if($pray <= 3000){
                $newPray = $pray;
            }else{
                $newPray = 3000;
            }
            if($newPray > 0)
            {
                 pay_award_mail(
                    $player_id
                    ,0
                    ,0
                    ,"祈福奖励"
                    ,"您当前单笔充值金额为{$pay_gold}元宝,祈福倍数为{$playerPray['mult']}倍，获得额外返还{$newPray}元宝（最高返还3000元宝）,祝您游戏愉快~"
                    ,0
                    ,$newPray
                );
                //mdb的update 用法不一样
                $mdb->update(pay_pray,array('player_id'=>$player_id),array('mult'=>-1,'ctime'=>0));
            }
        }
        
    }
}

/**
 * 日常充值活动奖励
 * @param $actItem charge_activity表一条记录
 * @param $player_id 玩家角色ID
 * @return void
 */
function pay_activity_award($actItem,$player_id)
{
    /**
     * `type` tinyint(1) NOT NULL COMMENT '1单笔 ,2累积',
  `items` text COMMENT '物品id:数量:是否绑定',
     */
    if(!$actItem['items'])
        return false;
    $title = $actItem['title'];
    $content = $actItem['content'];
    //物品基础信息
    $baseGoodsName = Goods::getGoodsNameList();

    $exp = explode("\n", $actItem['items']);
    foreach($exp as $line)
    {
        $line = trim($line);
        if(!$line)continue;
        list($gid,$gnum,$bind) = explode(":", $line);
        if($gid<1 || $gnum<1 || !$baseGoodsName[$gid])
        {
            continue;
        }
        //bind，类型（0：绑定物品的系统邮件、1：系统邮件、2：私人邮件）', 1：表示的是 系统邮件，不理物品是否绑定
        pay_award_mail(
            $player_id
            ,(int)$gid
            ,(int)$gnum
            ,$title
            ,str_replace('[ITEMINFO]',"{$baseGoodsName[$gid]}x{$gnum}", $content)
            ,(int)$bind
        );
    }

    $mdb = Mdb::getInstance('mongo');
    $insert = array();
    $insert['id'] = (int)$mdb->getAutoId("charge_activity_log");
    $insert['ca_st'] = (int)$actItem['st'];
    $insert['ca_id'] = (int)$actItem['id'];
    $insert['ctime'] = time();
    $insert['role_id'] = (int)$player_id;
    
    $mdb->insert("charge_activity_log", $insert);

}

/*
 * 充值互动邮件发送物品
 */
function pay_award_mail($player_id,$goods_id,$num,$title,$content,$type = 1,$gold = 0)
{
    $dbConn = DbAgent::getInstance("mongo");
    //type，类型（0：绑定物品的系统邮件、1：系统邮件、2：私人邮件）',
    //      1：表示的是 系统邮件，不理物品是否绑定
    $insertArray_mongo['type'] = $type;
    $insertArray_mongo['state'] = 2;
    $insertArray_mongo['timestamp'] = time();
    $insertArray_mongo['sname'] = "系统";
    $insertArray_mongo['uid'] = intval($player_id);
    $insertArray_mongo['title'] = $title;
    $insertArray_mongo['content'] = $content;
    $insertArray_mongo['gid'] = 0;
    $insertArray_mongo['goodtype_id'] = $goods_id;
    $insertArray_mongo['goods_num'] = $num;
    $insertArray_mongo['coin'] = 0;
    $insertArray_mongo['gold'] = $gold;
    $insertArray_mongo['id'] = $dbConn->getAutoId_mongodb(mail, "id");
    $dbConn->insert_mongodb(mail, $insertArray_mongo);
    
    //写入log_mail表中
    $rows = $dbConn->fetchOne_mongodb("player",array("id"=>$player_id),array("nickname"),null);
    $log_mail['time'] = time();
    $log_mail['sname'] = "系统";
    $log_mail['uid'] = intval($player_id);
    $log_mail['uname'] = $rows['nickname'];
    $log_mail['gid'] = 0;
    $log_mail['goods_id'] = $goods_id;
    $log_mail['goods_num'] = $num;
    $log_mail['coin'] = 0;
    $log_mail['gold'] = $gold;
    $log_mail['act'] = 1;
    $log_mail['id'] = $dbConn->getAutoId_mongodb(log_mail, "id");
    $dbConn->insert_mongodb(log_mail, $log_mail);
}
/**
 * 添加充值积分
 */
function add_pay_score($player_id,$gold)
{
    //开关
    if(1 == 2){
        $dbConn = DbAgent::getInstance("mongo");
        $row = $dbConn -> fetchOne_mongodb(sub_score,array("player_id"=>$player_id),array("player_id","money"),null,null);
        if($row["player_id"] > 0)
        {
            $newScore = intval($row["money"]) + intval($gold);
            $dbConn -> update_mongodb(sub_score,array("player_id"=>$player_id),array('$set'=>array("money"=>$newScore)));
        }else{
            $dbConn->insert_mongodb(sub_score, array("player_id"=>$player_id,"money"=>intval($gold),"sub_score"=>0)); 
        }
    }
}

/*
 * 合服充值互动
 */
function union_pay_award($player_id,$gold ,$pay_time)
{
    //开关
    if( 1== 1)
    {
        $begTime = 1321675200;//11月19日12  1321675200
        $endTime = 1321848000;//11月21日12  1321848000
        
        if($pay_time > $begTime && $pay_time < $endTime){
            if($gold >= 1000 && $gold <= 2999)
            {
                $title = "合服充值1000元宝回馈奖励";
                $content = "单笔充值达1000元宝将获得：经脉保护符*1、四级紫水晶*2、紫色附魔石*2、神兽蛋*2。感谢你对我们游戏的支持，祝你游戏愉快！";
                pay_award_mail($player_id,22007,1,$title,$content , 0);
                pay_award_mail($player_id,21500,2,$title,$content , 0);
                pay_award_mail($player_id,21023,2,$title,$content , 0);
                pay_award_mail($player_id,24800,2,$title,$content , 0);
            }elseif($gold >= 3000 && $gold <= 4999)
            {
                $title = "合服充值3000元宝回馈奖励";
                $content = "单笔充值达3000元宝将获得：经脉保护符*3、四级紫水晶*7、紫色附魔石*7、神兽蛋*7、一级攻击宝石*4。感谢你对我们游戏的支持，祝你游戏愉快！";
                pay_award_mail($player_id,22007,3,$title,$content , 0);
                pay_award_mail($player_id,21500,7,$title,$content , 0);
                pay_award_mail($player_id,21023,7,$title,$content , 0);
                pay_award_mail($player_id,24800,7,$title,$content , 0);
                pay_award_mail($player_id,21320,4,$title,$content , 0);
            }elseif($gold >= 5000 && $gold <= 9999)
            {
                $title = "合服充值5000元宝回馈奖励";
                $content = "单笔充值达5000元宝将获得：经脉保护符*5、四级紫水晶*12、紫色附魔石*15、神兽蛋*15、一级攻击宝石*12。感谢你对我们游戏的支持，祝你游戏愉快！";
                pay_award_mail($player_id,22007,5,$title,$content , 0);
                pay_award_mail($player_id,21500,12,$title,$content , 0);
                pay_award_mail($player_id,21023,15,$title,$content , 0);
                pay_award_mail($player_id,24800,15,$title,$content , 0);
                pay_award_mail($player_id,21320,12,$title,$content , 0);
            }elseif($gold >= 10000 && $gold <= 19999)
            {
                $title = "合服充值10000元宝回馈奖励";
                $content = "单笔充值达10000元宝将获得：经脉保护符*12、四级紫水晶*25、紫色附魔石*35、神兽蛋*35、一级攻击宝石*40。感谢你对我们游戏的支持，祝你游戏愉快！";
                pay_award_mail($player_id,22007,12,$title,$content , 0);
                pay_award_mail($player_id,21500,25,$title,$content , 0);
                pay_award_mail($player_id,21023,35,$title,$content , 0);
                pay_award_mail($player_id,24800,35,$title,$content , 0);
                pay_award_mail($player_id,21320,40,$title,$content , 0);
            }elseif($gold >= 20000)
            {
                $title = "合服充值20000元宝回馈奖励";
                $content = "单笔充值达20000元宝将获得：经脉保护符*25、四级紫水晶*40、紫色附魔石*70、神兽蛋*70、一级攻击宝石*100。感谢你对我们游戏的支持，祝你游戏愉快！";
                pay_award_mail($player_id,22007,25,$title,$content , 0);
                pay_award_mail($player_id,21500,40,$title,$content , 0);
                pay_award_mail($player_id,21023,70,$title,$content , 0);
                pay_award_mail($player_id,24800,70,$title,$content , 0);
                pay_award_mail($player_id,21320,100,$title,$content , 0);
            }
        }   
    }
    
}